import sandwich 
import kmeans
import rttDiff
import difference
import kmeansplus
from logger import Logger
from math import log
from numpy import *

'''
to study:
list directory tuple sort lambda [[] for ....]
'''

K = 2
logger = Logger("./log.config","scantopo")

def run():
    logger.debug("----------run()--------\n")
    print "----------------------Dst------------------\n"
    hosts=[]
    for i in range(2,14):
        hosts.append(str(i))

    print "----------------------RTT------------------\n"
    rtt = rttDiff.testDiff(hosts,20)
    #print rtt
    host_rttdic = {i+2:rtt[i] for i in range(len(rtt))}
    #print host_rttdic
    host_rttlist =  sorted(host_rttdic.items(), key = lambda host_rttdic:host_rttdic[1])
    sortedrtt = [host_rttlist[i][1] for i in range(len(host_rttlist))]

    print "----------------------Layers------------------\n"
    print sortedrtt
    #sortedrtt0=map(lambda x:x*1.5,sortedrtt)
    #rttcluster = kmeans.run(sortedrtt, K)
    #rttcluster = difference.difference(sortedrtt)
    rttcluster = kmeansplus.run(sortedrtt, K)
    print ("********di******")
    print rttcluster
    layers = [[] for i in range(K)]
    classnumber = 0
    classid = int(rttcluster[:,0][0])
    for i in range(rttcluster.shape[0]):
        if classid != int(rttcluster[:,0][i]):
        	classnumber = classnumber+1
        	classid = int(rttcluster[:,0][i])
        hostid = host_rttlist[i][0] 
        layers[classnumber].append(hostid)
    print "Result : ",layers
    '''
    tmpl = []
    val = rttcluster[:,0][0]
    for i in range(rttcluster.shape[0]):
        if rttcluster[:,0][i] == val:
        	tmpl.append(int(i)+2)
        	#print tmpl
        else:
        	layers.append(tmpl)
        	tmpl = []
        	tmpl.append(int(i)+2)
        	val = rttcluster[:,0][i]
    layers.append(tmpl)
    print layers
'''
    print "------------------Groups (In Layer)------------------\n"
    landg = []
    for layer in layers:
        layer.sort()
	#print layer
        lhx,lhy,diffxy = sandwich.div(layer)
        #print lhx,'\n',lhy,'\n',diffxy

        xy_diffdic = {(lhx[i],lhy[i]):diffxy[i] for i in range(len(diffxy))}
	#print xy_diffdic
	#print("********lll*********")
	#print xy_diffdic[1]
        xy_difflist =  sorted(xy_diffdic.items(), key = lambda xy_diffdic:xy_diffdic[1], reverse = True)
	#print xy_difflist
        sorteddiffxy = [xy_difflist[i][1] for i in range(len(xy_difflist))]
        #print sorteddiffxy
	print sorteddiffxy
	#sorteddiffxy1=map(lambda x:x*1.5,sorteddiffxy)
        #xycluster = kmeans.run(sorteddiffxy,K)
	xycluster = kmeansplus.run(sorteddiffxy,K)
	#print(len(xycluster))
	#xycluster = matrix
	if int(xycluster[:,0][0]) == int(xycluster[:,0][len(xycluster)-1]):
		print "error,do kmeas again"		
		#xycluster = kmeans.run(sorteddiffxy,K)
		xycluster = kmeansplus.run(sorteddiffxy,K)
        layc = [[] for i in range(K)]
        classnum = 0
        claid = int(xycluster[:,0][0])
        for i in range(xycluster.shape[0]):
            if claid != int(xycluster[:,0][i]):
                classnum = classnum + 1
                claid = int(xycluster[:,0][i])
            xy = xy_difflist[i][0] 
            layc[classnum].append(xy)
        print layc[0]
        
        l = layc[0]
        f=[-1 for i in range(20)]
        result = [[] for i in range(len(l))]
        index = 0
        
        for i in range(len(l)):
            fir = l[i][0]
            sec = l[i][1]
            if f[sec] != -1:
                fir,sec = sec,fir 
            if f[fir]==-1:
                result[index].append(fir)
                result[index].append(sec)
                f[fir] = index
                f[sec] = index
                index = index + 1
            else:
                if sec not in result[f[fir]]:
                    result[f[fir]].append(sec)
                    f[sec] = f[fir]
        groups = result[0:index]
        #print groups

        glist = []
        for group in groups:
            glist = glist + group
        if len(glist) < len(layer):
            single = list(set(layer).difference(set(glist)))
            for h in single:
                groups.append([h])
        #print groups
        landg.append(groups)
    print "Result : ",landg

        #return result[0:index]

    print "----------------------Tree------------------\n"
    tree(landg)

def tree(landg):
    logger.debug("---------landg()------------\n")
    #print len(landg)
    for no in range(len(landg)-1):
        lhx,lhy,diffxy = sandwich.con(landg[no], landg[no+1])
        #print lhx,'\n',lhy,'\n',diffxy

        xy_diffdic = {(lhx[i],lhy[i]):diffxy[i] for i in range(len(diffxy))}
        xy_difflist =  sorted(xy_diffdic.items(), key = lambda xy_diffdic:xy_diffdic[1], reverse = True)
        sorteddiffxy = [xy_difflist[i][1] for i in range(len(xy_difflist))]
        #print xy_difflist
	print sorteddiffxy
	#sorteddiffxy2=map(lambda x:x*1.5,sorteddiffxy)
        #xycluster = kmeans.run(sorteddiffxy,K)
	xycluster = kmeansplus.run(sorteddiffxy,K)
	#print xycluster

	if int(xycluster[:,0][0]) == int(xycluster[:,0][len(xycluster)-1]):
		print "error,do kmeas again"		
		#xycluster = kmeans.run(sorteddiffxy,K)
		xycluster = kmeansplus.run(sorteddiffxy,K)
        layc = [[] for i in range(K)]
        classnum = 0
        claid = int(xycluster[:,0][0])
        for i in range(xycluster.shape[0]):
            if claid != int(xycluster[:,0][i]):
                classnum = classnum + 1
                claid = int(xycluster[:,0][i])
            xy = xy_difflist[i][0] 
            layc[classnum].append(xy)
	    #print layc
        print "Result :\n","L",no,"<--->","L",no+1," : ",layc[0]

if __name__ =="__main__":
    run()
    #landg = [[[5,6],[2,3],[4]], [[12,13],[9,10,11],[7,8]]]
    #tree(landg)



